#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
fi

APP_TARGET_DIR_NAME="video-subtitle-remover"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:20"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_REPO_URL=${GIT_HOST}/YaoFANGUK/video-subtitle-remover
export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:40"

conda --version
echo "lmdprogress:41"
cd "$CURRENT_APP_PATH"

export CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv and remove it"
    rm -rf "$CONDA_PREFIX"
fi
export PYTHON_VER_ENV="3.12"
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV -y

cd "$CURRENT_APP_PATH"

echo "lmdprogress:50"
if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
#   conda_run_pip_install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
#   conda_run_pip_install torch==2.8.0 torchvision torchaudio
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
  conda_run_conda_forge_install ffmpeg
elif current_os_is_windows; then
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_ffmpeg.sh"
fi

echo "lmdprogress:75"

if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    grep -vE 'onnxruntime-gpu==|onnxruntime-directml==' requirements.txt > requirements-temp.txt
    conda_run_pip_install -r requirements-temp.txt onnxruntime paddlepaddle
elif current_os_is_windows; then
    if [[ "$ARCH_AND_GPU_INFO" == "nvidia_gpu" ]]; then
        conda_run_pip_install protobuf==3.20.0
        grep -vE 'protobuf==' requirements.txt > requirements-temp2.txt
        conda_run_pip_install -r requirements-temp2.txt paddlepaddle-gpu
    else 
        conda_run_pip_install -r requirements.txt paddlepaddle
    fi
fi

echo "lmdprogress:100"
